﻿#region Using Directives

using System;
using System.IO;
using System.Windows.Forms;
using System.Globalization;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.RecipeFramework.Library;
using Microsoft.Practices.RecipeFramework.Services;
using Microsoft.Practices.RecipeFramework.VisualStudio;
using Microsoft.Practices.RecipeFramework.VisualStudio.Templates;
using EnvDTE;
using System.Xml;

#endregion

namespace SteriaMummert.SharePoint.SoftwareFactoryLite.Actions
{
    /// <summary>
    /// Adds text from a t4 template to a given xml node in an xml file
    /// </summary>
    [ServiceDependency(typeof(DTE))]
    public class AddContentToXmlNode : ConfigurableAction
    {
        private ProjectItem destItem;
        private string _Content;
        private string _TargetNode;
        private string _TargetNamespace;

        /// <summary>
        /// Specifies the filename name of the xml file in the project 
        /// </summary>
        [Input(Required = true)]
        public ProjectItem Item
        {
            get { return destItem; }
            set { destItem = value; }
        }

      
        [Input(Required = false)]
        public string TargetNamespace
        {
            get { return _TargetNamespace; }
            set { _TargetNamespace = value; }
        }

        [Input(Required = false)]
        public string TargetNode
        {
            get { return _TargetNode; }
            set { _TargetNode = value; }
        }
   

        [Input(Required = true)]
        public string Content
        {
            get { return _Content; }
            set { _Content = value; }
        }

        public override void Execute()
        {
            try
            {                
                XmlDocument field = new XmlDocument();
                field.LoadXml(Content);             

                string path = destItem.Properties.Item("FullPath").Value.ToString();
                XmlDocument doc = new XmlDocument();
                doc.Load(path);

                XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
                docFrag.InnerXml = Content;

                XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                nsmgr.AddNamespace("ns", TargetNamespace);
                
                XmlNode node = doc.SelectSingleNode(TargetNode, nsmgr);
                if (node != null)
                {
                    node.AppendChild(docFrag); 
                    doc.Save(path);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public override void Undo()
        {
        }
    }
}